package com.zs.admin.service.wisdbook.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import com.zs.admin.service.wisdbook.IWisdbookMarkerImgService;
import com.zs.admin.service.wisdbook.IWisdbookPageMarkService;
import com.zs.admin.service.wisdbook.IWisdbookPageService;
import com.zs.admin.vo.wisdbook.WisdbookPageDetailVo;
import com.zs.admin.vo.wisdbook.WisdbookPageMarkDetailVo;
import com.zs.admin.vo.wisdbook.WisdbookPageMarkListedVo;
import com.zs.common.mapper.WisdbookPageMarkMapper;
import com.zs.common.util.ImageUtil;
import com.zs.common.util.YmlUtils;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WisdbookMarkerImgServiceImpl implements IWisdbookMarkerImgService {
    @Autowired
    IWisdbookPageMarkService wisdbookPageMarkService;

    @Autowired
    IWisdbookPageService wisdbookPageService;

    @Resource
    WisdbookPageMarkMapper wisdbookPageMarkMapper;

    @Override
    public void render(HttpServletResponse response, String markId) {

        WisdbookPageMarkDetailVo vo = wisdbookPageMarkService.detail(markId);
        List<WisdbookPageMarkListedVo> childs = wisdbookPageMarkService.listByPid(markId);

        WisdbookPageDetailVo pid =wisdbookPageService.detail(vo.getPageId());

        List<Map<String,String>> pages= Lists.newArrayList();

        Map map = Maps.newLinkedHashMap();
        map.put("imgPath",pid.getPageImg());
        map.put("rectJson",vo.getShape().toJSONString());
        pages.add(map);

        childs.forEach(wisdbookPageMarkListedVo -> {
            Map p = Maps.newLinkedHashMap();

            if (vo.getPageId() == wisdbookPageMarkListedVo.getPageId()){
                p.put("imgPath",pid.getPageImg());
                p.put("rectJson",vo.getShape().toJSONString());
            }else{
                WisdbookPageDetailVo po =wisdbookPageService.detail(wisdbookPageMarkListedVo.getPageId());
                p.put("imgPath",po.getPageImg());
                p.put("rectJson",wisdbookPageMarkListedVo.getShape().toJSONString());
            }

            pages.add(p);
        });
        response.setHeader("Content-Type","image/png");
        renderOssUrl(response,pages);
    }

    private void renderOssUrl(HttpServletResponse response,List<Map<String,String>> pages)  {

        String ossPrefix= YmlUtils.get("ossResource.endpoint")+"wisdomebook/";
        List<String> ossUrls = Lists.newArrayList();

        for (Map<String,String> mp:pages) {
            String img = mp.get("imgPath");
            String json = mp.get("rectJson");
            JSONObject js= JSON.parseObject(json);
            int height = js.getFloat("height").intValue();
            int width = js.getFloat("width").intValue();
            int x = js.getFloat("x").intValue();
            int y = js.getFloat("y").intValue();
            String url = img+String.format("?x-oss-process=image/crop,x_%d,y_%d,w_%d,h_%d",x,y,width,height);
            log.debug(url);
            ossUrls.add(url);
        }

        try {
            if (ossUrls.size()==1) {
                IOUtils.copy( Requests.get(ossUrls.get(0)).send().getInput(),response.getOutputStream());
                //response.sendRedirect(ossUrls.get(0));
            }else{
                BufferedImage image = ImageUtil.mergeUrls(ossUrls,true,null);
                ImageIO.write(image,"png",response.getOutputStream());
            }

        } catch (IOException e) {

            try {
                response.getWriter().write("");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

    }


}
